package com.example.blog.modules.system.service.impl;

import com.example.blog.common.exception.ServiceException;
import com.example.blog.modules.system.dto.FileUploadDTO;
import com.example.blog.modules.system.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class LocalFileServiceImpl implements FileService {

    @Value("${blog.upload.path}")
    private String uploadPath;

    @Value("${blog.upload.url-prefix}")
    private String urlPrefix;

    @Override
    public FileUploadDTO uploadFile(MultipartFile file, String directory) {
        try {
            String fileName = generateFileName(file.getOriginalFilename());
            String fullPath = createUploadPath(directory);
            Path targetPath = Paths.get(fullPath, fileName);
            
            Files.createDirectories(targetPath.getParent());
            Files.copy(file.getInputStream(), targetPath);
            
            return createFileUploadDTO(file, fileName, directory);
        } catch (IOException e) {
            throw new ServiceException("文件上传失败：" + e.getMessage());
        }
    }

    @Override
    public List<FileUploadDTO> uploadFiles(List<MultipartFile> files, String directory) {
        List<FileUploadDTO> results = new ArrayList<>();
        for (MultipartFile file : files) {
            results.add(uploadFile(file, directory));
        }
        return results;
    }

    @Override
    public void deleteFile(String fileUrl) {
        if (StringUtils.hasText(fileUrl) && fileUrl.startsWith(urlPrefix)) {
            String relativePath = fileUrl.substring(urlPrefix.length());
            Path filePath = Paths.get(uploadPath, relativePath);
            try {
                Files.deleteIfExists(filePath);
            } catch (IOException e) {
                throw new ServiceException("文件删除失败：" + e.getMessage());
            }
        }
    }

    @Override
    public String getFileUrl(String fileName, String directory) {
        return urlPrefix + "/" + directory + "/" + fileName;
    }

    private String generateFileName(String originalFilename) {
        String extension = StringUtils.getFilenameExtension(originalFilename);
        return UUID.randomUUID().toString() + (extension != null ? "." + extension : "");
    }

    private String createUploadPath(String directory) {
        return Paths.get(uploadPath, directory).toString();
    }

    private FileUploadDTO createFileUploadDTO(MultipartFile file, String fileName, String directory) {
        FileUploadDTO dto = new FileUploadDTO();
        dto.setFileName(fileName);
        dto.setOriginalFileName(file.getOriginalFilename());
        dto.setUrl(getFileUrl(fileName, directory));
        dto.setContentType(file.getContentType());
        dto.setSize(file.getSize());
        return dto;
    }
} 